package com.maimao.order.job;

import cn.hutool.core.util.ObjectUtil;
import com.maimao.core.model.resp.Result;
import com.maimao.core.utils.DateUtils;
import com.maimao.model.order.es.EsOrder;
import com.maimao.model.user.Shop;
import com.maimao.order.client.EsClient;
import com.maimao.order.client.ShopClient;
import com.maimao.order.mapper.OrderMapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.reflect.generics.tree.ReturnType;

import java.util.List;
import java.util.UUID;

/**
 * 同步订单数据到Es 每小时同步一次
 *
 * @author MaoLin Wang
 * @date 2021/3/29 9:21 下午
 */
@Component
@Slf4j
public class SyncOrder2EsJobHandler {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private EsClient esClient;

    @Autowired
    private ShopClient shopClient;

    @XxlJob("SyncOrder2EsJobHandler")
    public ReturnT syncOrder2Es() throws Exception {
        XxlJobHelper.log("准备同步订单数据 - {}", DateUtils.now());
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();
        List<EsOrder> esOrders = orderMapper.selectEsOrderBySharding(shardIndex, shardTotal);
        String syncNo = UUID.randomUUID().toString();
        XxlJobHelper.log("同步序号 —— {} ,查询到要同步的订单数据 - {} , 数量 - {}", syncNo, esOrders, esOrders.size());
        log.info("查询到要同步的订单数据 - {} , 数量 - {}", esOrders, esOrders.size());

        if (ObjectUtil.isNotEmpty(esOrders)) {
            esOrders.forEach(esOrder -> {
                esOrder.getOrderShopList().forEach(esOrderShop -> {
                    Result<Shop> shopResult = shopClient.queryByIdIn(Long.valueOf(esOrderShop.getShopId()));
                    if (shopResult != null && shopResult.getData() != null) {
                        esOrderShop.setShopName(shopResult.getData().getName());
                    }
                });
            });
            Result result = esClient.saveBatch(esOrders);
            if (result != null && result.getData() != null) {
                boolean success = (boolean) result.getData();
                if (success) {
                    XxlJobHelper.log("同步订单数据成功 syn序号- {} , 数量 - {}", syncNo, esOrders.size());
                    return ReturnT.SUCCESS;

                } else {
                    XxlJobHelper.log("同步订单数据失败 syn序号- {} , 数量 - {} ,准备重试", syncNo, esOrders.size());
                    int retryCount = 0;
                    while (++retryCount <= 3 && !success) {
                        XxlJobHelper.log("syn序号- {} , 第{}次重试", syncNo, retryCount, esOrders.size());

                        Result res = esClient.saveBatch(esOrders);
                        if (res != null && res.getData() != null) {
                            success = (boolean) res.getData();
                            if (success) {
                                XxlJobHelper.log("syn序号- {} , 第{}次重试成功 ", syncNo, retryCount, esOrders.size());
                            }

                        } else {
                            success = false;
                        }
                    }
                    return success ? ReturnT.SUCCESS : ReturnT.FAIL;

                }
            }
        }
        return ReturnT.SUCCESS;

        // default success
    }
}
